//
//  CZNewFeatureViewController.swift
//  GZWeibo009
//
//  Created by gzxzmac on 16/3/22.
//  Copyright © 2016年 gzxzmac. All rights reserved.
//

import UIKit

import SnapKit

private let reuseIdentifier = "Cell"

class CZNewFeatureViewController: UICollectionViewController {
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 流水布局
    let layout = UICollectionViewFlowLayout()
    
    // 父类没有init()这个构造函数,子类不需要使用overrid
    init() {
        super.init(collectionViewLayout: layout)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        prepareCollectionView()
    }
    
    /// collectionView的设置
    private func prepareCollectionView() {
        // 设置layout参数
        layout.itemSize = UIScreen.mainScreen().bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
        
        // 注册cell
        // UICollectionViewCell.self ==> [UICollectionViewCell class]
        collectionView?.registerClass(CZNewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }
}

// MARK: - collectionView数据源和代理方法
extension CZNewFeatureViewController {
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return CZNewFeatuerPageCount
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        // 从缓存池里面获取cell
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CZNewFeatureCell
        
        cell.backgroundColor = UIColor.random()
        
        // 设置cell要显示的页码
        cell.index = indexPath.item
        
        // 不能在这里调用这个动画
        //        cell.startButtonAnimation()
        
        return cell
    }
    
    override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        // 计算当前页
        let page = Int(scrollView.contentOffset.x / UIScreen.mainScreen().bounds.width)
        print("page: \(page)")
        // 判断当前是否是最后一页
        if page == CZNewFeatuerPageCount - 1 {
            
            // 创建indexPath
            let indexPath = NSIndexPath(forItem: page, inSection: 0)
            
            // 获取indexPath对应的cell
            let cell = collectionView?.cellForItemAtIndexPath(indexPath) as! CZNewFeatureCell
            
            // 让开始按钮动画
            cell.startButtonAnimation()
        }
    }
}

// 自定义的cell
class CZNewFeatureCell: UICollectionViewCell {
    
    // MARK: - 属性
    /// 当前显示的页数
    var index: Int = 0 {
        didSet {
            // 在控制器设置了页码之后,我们根据页码来显示对应的图片
            // 图片1, 2, 3, 4
            // index0 ,1 ,2 ,3
            bkgImageView.image = UIImage(named: "new_feature_\(index + 1)")
            
            // 只要cell要设置背景图片,就隐藏按钮
            startButton.hidden = true
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        prepareUI()
    }
    
    /// 开始按钮动画
    func startButtonAnimation() {
        startButton.hidden = false
        
        // 在开始动画之前,将transform Scale设置为0
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        
        UIView.animateWithDuration(1, delay: 0.1, usingSpringWithDamping: 0.5, initialSpringVelocity: 6, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            self.startButton.transform = CGAffineTransformIdentity
            }, completion: nil)
        
    }
    
    // MARK: - 按钮点击事件
    func didClickStartButton() {
        // 切换到CZMainViewController
        AppDelegate.outSwitchRootViewController(CZMainViewController())
        //        let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
        //        appDelegate?.switchRootViewController(CZMainViewController())
        //        appDelegate?.window?.rootViewController = CZMainViewController()
    }
    
    // 一般是设置frame.最好不要添加约束,约束会添加2次,当约束改变的时候会出现冲突
    override func layoutSubviews() {
        super.layoutSubviews()
    }
    
    private func prepareUI() {
        // 1.添加子控件, 注意往contentView里面添加
        contentView.addSubview(bkgImageView)
        contentView.addSubview(startButton)
        
        // 2.添加约束
        bkgImageView.translatesAutoresizingMaskIntoConstraints = false
        startButton.translatesAutoresizingMaskIntoConstraints = false
        
        // 背景
        bkgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
//        contentView.addConstraint(NSLayoutConstraint(item: bkgImageView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0))
//        
//        contentView.addConstraint(NSLayoutConstraint(item: bkgImageView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
//        
//        contentView.addConstraint(NSLayoutConstraint(item: bkgImageView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0))
//        
//        contentView.addConstraint(NSLayoutConstraint(item: bkgImageView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        
        // 开始按钮
//        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
//        contentView.addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: -160))
        startButton.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView).offset(-160)
        }
        
    }
    
    // MARK: - 懒加载
    /// 背景
    private lazy var bkgImageView: UIImageView = UIImageView(image: UIImage(named: "new_feature_1"))
    
    private lazy var startButton: UIButton = {
        let button = UIButton()
        
        // 设置按钮
        button.setTitle("开始体验", forState: UIControlState.Normal)
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        button.addTarget(self, action: "didClickStartButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
}
